#include <stdlib.h>
#include <string.h>

#include <iostream>
using namespace std;

char *intToStr(int num, char ret[32])
{
	int i = 0;
	char temp[4];
	while (num != 0)
	{
		temp[i++] = num % 10 + '0';
		num = num / 10;
	}

	temp[i] = '\0';

	i--;
	int j = 0;
	while (i >=0 )
	{
		ret[j++] = temp[i--];
	}

	ret[j] = '\0';

	return ret;
}

unsigned int strToInt(const char *pStr)
{
	if (pStr == NULL)
	{
		return -1;
	}

	int ret = 0;
	while (*pStr != '\0')
	{
		if (*pStr < '0' || *pStr > '9')
		{
			return -1;
		}

		ret = ret * 10 + (*pStr - '0');
		pStr++;
	}

	return ret;
}

unsigned int ipton(const char *ip)
{
	if (ip == NULL)
	{
		return -1;
	}

	char seg[4] = {'\0'};
	int i = 0;
	unsigned int ret = 0, shift = 24;

	while (*ip != '\0')
	{
		if ((*ip == '.' && i <= 3))
		{
			int tmp = strToInt(seg); //strToInt already check the value is digital
			if (tmp == -1)
			{
				return -1;
			}

			ret |= (tmp << shift);
			shift -= 8;
			memset(seg, '\0', 4);
			i = 0;
			ip++;
			continue;
		}

		if (i >= 3) //each section should only have three character
		{
			cout << "ip is error" << endl;
			return -1;
		}

		seg[i++] = *(ip++);
	}

	int tmp = strToInt(seg); //strToInt already check the value is digital
	if (tmp == -1)
	{
		return -1;
	}

	ret |= tmp;

	return ret;
}

char *ntoip(int num)
{
	char *pRet = new char[17];
	char *pTmp = pRet;

	memset(pTmp, '\0', 17);

	int shift = 24;
	char tmp[4] = {'\0'};

	for (int j = 0; j < 3; j++)
	{
		int temp = (num >> shift) & 0x000000FF;
		shift -= 8;
		intToStr(temp, tmp);
		for (int t = 0; t < 4; t++)
		{
			if (tmp[t] != '\0')
			{
				*(pTmp++) = tmp[t];
			}
		}
		*(pTmp++) = '.';
	}

	intToStr(num & 0x000000FF, tmp);
	for (int t = 0; t < 4; t++)
	{
		if (tmp[t] != '\0')
		{
			*(pTmp++) = tmp[t];
		}
	}

	return pRet;
}

void strToIntTest()
{
	cout << "String to Int test: " << endl;
	char str[32] = {'\0'};

	cout << "int [356] change to string: " << intToStr(356, str) << endl;

	cout << "string \"123455\" change to Int: " << strToInt("123455") << endl;

	cout << "string \"123h55\" change to Int: " << strToInt("123h55") << endl;
}

void ipToIntTest()
{
	cout << "[192.168.2.156] cover to Int: " << ipton("192.168.2.156") << endl;
	cout << "(3232236188) covert to ip: " << ntoip(3232236188) << endl;
}
